package com.qen.typehandler;

import org.beetl.sql.core.mapping.type.JavaSqlTypeHandler;
import org.beetl.sql.core.mapping.type.PrimitiveValue;
import org.beetl.sql.core.mapping.type.ReadTypeParameter;
import org.beetl.sql.core.mapping.type.WriteTypeParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author licz
 * @title BigIntegerTypeHandler
 * @date 2024/9/2 11:24
 * @description BigInteger类型处理器
 */
public class BigIntegerTypeHandler extends JavaSqlTypeHandler implements PrimitiveValue {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Override
    public Object getValue(ReadTypeParameter typePara) throws SQLException {
        ResultSet rs = typePara.rs;

        long a = rs.getLong(typePara.index);
        if (a != 0) {
            //先判断0有助于提升性能
            return BigInteger.valueOf(a);
        } else if (rs.wasNull()) {
            if (typePara.isPrimitive()) {
                return getDefaultValue();
            } else {
                return null;
            }
        } else {
            return BigInteger.valueOf(a);
        }

    }
    @Override
    public Object getDefaultValue() {
        return BigInteger.valueOf(0L);
    }
    @Override
    public void setParameter(WriteTypeParameter writeTypeParameter, Object obj) throws SQLException {
        long value = 0;
        BigInteger bigInteger = (BigInteger) obj;
        try {
            value = bigInteger.longValueExact();
        } catch (ArithmeticException e) {
            log.error("BigInteger 超出 long 范围");
            throw e;
        }
        writeTypeParameter.getPs().setLong(writeTypeParameter.getIndex(),value);
    }
}
